package cn.qicaiwang.open.websocket.rabbitmq;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;

import cn.qicaiwang.open.common.constant.Constants;
import cn.qicaiwang.open.common.entity.CrmMessage;
import cn.qicaiwang.open.common.entity.CrmSession;
import cn.qicaiwang.open.common.entity.Message;
import cn.qicaiwang.open.system.model.entity.SystemUser;
import cn.qicaiwang.open.system.model.entity.SystemUserWechat;
import cn.qicaiwang.open.system.service.ISystemUserService;
import cn.qicaiwang.open.system.service.ISystemUserWechatService;
import cn.qicaiwang.open.websocket.common.Constant;
import cn.qicaiwang.open.websocket.service.ICrmMessageService;
import cn.qicaiwang.open.websocket.service.ICrmSessionService;
import cn.qicaiwang.open.websocket.utils.MessageUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.concurrent.Executor;

@Component
@RabbitListener(queues = Constants.RABBITMQ_DEFAULT_QUEUE)
public class CrmRabbitMQListener {
    @Autowired
    private ICrmSessionService crmSessionService;
    @Autowired
    private ICrmMessageService crmMessageService;
    @Autowired
    private ISystemUserService systemUserService;
    @Autowired
    private ISystemUserWechatService systemUserWechatService;
  /*  @Autowired
    private WxMpService wxMpService;*/
    @Autowired
    private MailAccount mailTemplate;
    @Autowired
    private Executor threadPoolTaskExecutor;

    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void callback(Message message){
        try {
            String fromUserId = message.getFromUserId();
            String toUserId = message.getToUserId();

            CrmSession session = crmSessionService.getByPartaker(fromUserId, toUserId);
            if(session == null){
                session = new CrmSession();
                session.setId(IdUtil.getSnowflakeNextIdStr());
                session.setSessionName(IdUtil.nanoId());//这里发起会话的名称
                session.setPromoter(fromUserId);
                session.setPartaker(toUserId);
                session.setIsGroup(0);
                session.setCreateBy(fromUserId);
                session.setCreateTime(new Date());
                session.setUpdateBy(fromUserId);
                session.setUpdateTime(new Date());
                crmSessionService.save(session);
            }else{
                CrmSession temp = new CrmSession();
                temp.setId(session.getId());
                temp.setUpdateBy(fromUserId);
                temp.setUpdateTime(new Date());
                crmSessionService.updateById(temp);
            }

            CrmMessage crmMessage = new CrmMessage();
            crmMessage.setId(message.getId());
            crmMessage.setSessionId(session.getId());
            crmMessage.setEvent(message.getEvent());
            crmMessage.setMsgType(message.getMsgType());
            crmMessage.setFromUserId(fromUserId);
            crmMessage.setToUserId(message.getToUserId());
            crmMessage.setMessageBodyType(message.getMessage().getType());
            crmMessage.setMessageBodyContent(message.getMessage().getContent());
            crmMessage.setStatus(0);
            crmMessage.setCreateBy(message.getFromUserId());
            crmMessage.setCreateTime(new Date());
            crmMessageService.save(crmMessage);

            threadPoolTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    // 微信消息
                    SystemUserWechat systemUserWechat = systemUserWechatService.selectOneByUserId(toUserId);
              /*      if(systemUserWechat != null && StrUtil.isNotBlank(systemUserWechat.getMpOpenId())){
                        try {
                            MessageUtil.sendWechatMessage(wxMpService, systemUserWechat.getMpOpenId(), message);
                        } catch (WxErrorException e) {
                            throw new RuntimeException(e);
                        }
                    }*/
                    // 邮件消息
                    SystemUser systemUser = systemUserService.getById(toUserId);
                    if(StrUtil.isNotBlank(systemUser.getEmail())){
                        //MessageUtil.sendEmailMessage(mailTemplate, systemUser.getEmail(), message);
                    }

                    // 站内消息
                    if(Constant.pool.containsKey(message.getToUserId()) && Constant.pool.get(message.getToUserId()) != null){
                        WebSocketSession session = Constant.pool.get(toUserId);
                        MessageUtil.sendMessage(session, message);
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
